package com.thinkit.cms.service.category;

import com.thinkit.cms.api.category.CategoryModelRelationService;
import com.thinkit.cms.api.site.SiteTemplateService;
import com.thinkit.cms.dto.category.CategoryModelRelationDto;
import com.thinkit.cms.entity.category.CategoryModelRelation;
import com.thinkit.cms.mapper.category.CategoryModelRelationMapper;
import com.thinkit.core.annotation.SiteMark;
import com.thinkit.core.base.BaseServiceImpl;
import com.thinkit.core.handler.CustomException;
import com.thinkit.utils.model.ApiResult;
import com.thinkit.utils.utils.Checker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 分类选择模型时关系表 该模型值 tk_model 表 不是 分类模型表 服务实现类
 * </p>
 *
 * @author LG
 * @since 2020-08-10
 */
@Service
public class CategoryModelRelationServiceImpl extends BaseServiceImpl<CategoryModelRelationDto, CategoryModelRelation, CategoryModelRelationMapper> implements CategoryModelRelationService {


    @Autowired
    SiteTemplateService siteTemplateService;

    @Transactional
    @SiteMark
    @Override
    public void saveBatch(List<CategoryModelRelationDto> vs) {
         if(Checker.BeNotEmpty(vs)){
             checkIsLegal(vs);
             String templateId = siteTemplateService.findTemplateId(getSiteId());
             baseMapper.deleteByCSId(getSiteId(),vs.get(0).getCategoryId(),templateId);
             saveOrUpdate(vs,templateId);
         }
    }

    @Override
    public String loadTemplatePath(Map<String, Object> params) {
        return baseMapper.loadTemplatePath(params);
    }

    @Override
    public String getTempPathByCategoryId(String categoryId, String modelId) {
        return baseMapper.getTempPathByCategoryId(categoryId,modelId,getSiteId());
    }


    private void saveOrUpdate(List<CategoryModelRelationDto> vs,String templateId){
        if(Checker.BeNotEmpty(vs)){
            for(CategoryModelRelationDto v:vs){
                v.setTemplateId(templateId);
            }
            super.insertBatch(vs);
        }
    }


    private void checkIsLegal(List<CategoryModelRelationDto> vs){
        for(CategoryModelRelationDto mr:vs){
            if(Checker.BeBlank(mr.getCategoryId())){
                 throw new CustomException(ApiResult.result(5031));
            }
            if(Checker.BeBlank(mr.getTemplatePath())){
                 throw new CustomException(ApiResult.result(5032));
            }
            mr.setTemplatePath(mr.getTemplatePath().replace("\\","/"));
        }
    }
}
